<template>
  <div class="column-detail-page w-75 mx-auto" v-if="columnData">
    <div class="column-info row mb-4 border-bottom pb-4 align-items-center">
      <div class="col-3 text-center">
        <img :src="columnData.avatar && columnData.avatar.fitUrl" :alt="columnData.title" class="rounded-circle border ">
      </div>
      <div class="col-9">
          <h4>{{columnData.title}}</h4>
        <p class="text-muted">{{columnData.description}}</p>
      </div>
    </div>
    <post-list :list="postsData"></post-list>
    <div class="d-flex justify-content-center w-100">
    <button class="btn btn-primary w-25 mx-auto mb-5 mt-2" @click="loadMorePage" v-if="!isLastPage">点击</button>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, ref } from 'vue'
import PostList from './PostList.vue'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { GlobalDataProps, ColumnProps } from '../store'
import { addColumnAvatar } from '../helps'
import { useLoadMore } from '../hooks/useLoadMore'
export default defineComponent({
  name: 'ColumnDetail',
  components: {
    PostList
  },
  setup () {
    const route = useRoute()
    const store = useStore<GlobalDataProps>()
    const id = ref(route.params.id)

    const totalVal = computed(() => store.state.posts.total)
    const currentPageComputed = computed(() => store.state.posts.loadedColumns[id.value as string])
    const { loadMorePage, isLastPage } = useLoadMore('getColumnsPost', totalVal, { currentPage: currentPageComputed.value?.currentPage + 1 || 2, pageSize: 5, id: id.value as string })

    onMounted(() => {
      store.dispatch('getColumnsOne', id.value)
      if (!currentPageComputed.value || Math.ceil(currentPageComputed.value.total / 5) !== currentPageComputed.value.currentPage) {
        store.dispatch('getColumnsPost', { id: id.value, currentPage: currentPageComputed.value?.currentPage || 1, pageSize: 5 })
      }
    })

    const columnData = computed(() => {
      const selectColumn = store.getters.getColumnById(id.value) as ColumnProps | undefined
      if (selectColumn) {
        addColumnAvatar(selectColumn, 100, 100)
      }
      return selectColumn
    })
    const postsData = computed(() => {
      return store.getters.getPostsByCid(id.value)
    })
    return { columnData, postsData, loadMorePage, isLastPage }
  }
})
</script>
